/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.NewReService;
import com.jeeplus.modules.fee.service.ProfitService;
import com.jeeplus.modules.fee.service.ReceivableService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fee.service.CostService;

/**
 * 应收附加费用Controller
 * @author 李超辉
 * @version 2018-04-17
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/cost")
public class CostController extends BaseController {

	@Autowired
	private CostService costService;
	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private ProfitService profitService;
	@Autowired
	private NewReService newReService;
	
	@ModelAttribute
	public Cost get(@RequestParam(required=false) String id) {
		Cost entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = costService.get(id);
		}
		if (entity == null){
			entity = new Cost();
		}
		return entity;
	}
	
	/**
	 * 应收附加费用列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/costList";
	}
	
		/**
	 * 应收附加费用列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "data")
	public Map<String, Object> data(Cost cost, HttpServletRequest request, HttpServletResponse response, Model model) {

		Page<Cost> page = costService.findPage(new Page<Cost>(request, response), cost);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应收附加费用表单页面
	 */
	@RequestMapping(value = "form")
	public String form(Cost cost, Model model,String i) {
        cost.setRecive(i);
		model.addAttribute("cost", cost);
		return "modules/fee/costForm";
	}

	/**
	 * 查看，增加，编辑应收附加费用表单页面
	 */
	@RequestMapping(value = "form1")
	public String form1(Cost cost, Model model,String i) {
		cost.setRecive(i);
		model.addAttribute("cost", cost);
		return "modules/fee/1/costForm";
	}
	/**
	 * 保存应收附加费用
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxJson save(Cost cost, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, cost)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		Receivable r=receivableService.get(cost.getRecive());
		Double e=Double.parseDouble(r.getFreight().replace(",",""));
		Double add=r.getAd();
		Double a=Double.parseDouble(cost.getMoney());
		NumberFormat nf = NumberFormat.getInstance();
		r.setFreight(nf.format(e+a).replaceAll(",",""));
		r.setAd(add+a);
		receivableService.save(r);
        Profit profit= profitService.findUniqueByProperty("pid",r.getPid());
        profit.setSr(r.getFreight());
        double sj=Double.parseDouble(profit.getSl())*Double.parseDouble(r.getFreight());
        double lr=Double.parseDouble(r.getFreight())-Double.parseDouble(profit.getZzc())-sj;
		DecimalFormat df = new DecimalFormat("0.00%");
		String lrl=df.format(lr/Double.parseDouble(r.getFreight()));
        profit.setLrl(lrl);
        profit.setSj(nf.format(sj).replaceAll(",",""));
        profit.setLr(nf.format(lr).replaceAll(",",""));
        profitService.save(profit);
		costService.save(cost);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存应收附加费用成功");
		return j;
	}

	/**
	 * 保存应收附加费用
	 */
	@ResponseBody
	@RequestMapping(value = "save1")
	public AjaxJson save1(Cost cost, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, cost)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		NewRe r=newReService.get(cost.getRecive());
		Double e=Double.parseDouble(r.getFreight().replace(",",""));
		Double add=Double.parseDouble(r.getAd());
		Double a=Double.parseDouble(cost.getMoney());
		NumberFormat nf = NumberFormat.getInstance();
		r.setFreight(nf.format(e+a).replaceAll(",",""));
		r.setAd(nf.format(add+a).replaceAll(",",""));
		newReService.save(r);
		costService.save(cost);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存应收附加费用成功");
		return j;
	}

	/**
	 * 删除应收附加费用
	 */
	@ResponseBody
	@RequiresPermissions("fee:cost:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Cost cost, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		costService.delete(cost);
		j.setMsg("删除应收附加费用成功");
		return j;
	}
	
	/**
	 * 批量删除应收附加费用
	 */
	@ResponseBody
	@RequiresPermissions("fee:cost:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			costService.delete(costService.get(id));
		}
		j.setMsg("删除应收附加费用成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:cost:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Cost cost, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收附加费用"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Cost> page = costService.findPage(new Page<Cost>(request, response, -1), cost);
    		new ExportExcel("应收附加费用", Cost.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收附加费用记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:cost:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Cost> list = ei.getDataList(Cost.class);
			for (Cost cost : list){
				try{
					costService.save(cost);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收附加费用记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收附加费用记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收附加费用失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/cost/?repage";
    }
	
	/**
	 * 下载导入应收附加费用数据模板
	 */
	@RequiresPermissions("fee:cost:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收附加费用数据导入模板.xlsx";
    		List<Cost> list = Lists.newArrayList(); 
    		new ExportExcel("应收附加费用数据", Cost.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/cost/?repage";
    }

}